<route lang="json5" type="page">
{
  layout: "tabbar",
  style: {
    navigationStyle: "custom",
    navigationBarTitleText: "商单&活动",
  },
}
</route>

<template>
  <view class="overflow-hidden bussines-container">
    <view class="bussies-bg"></view>
    <view
      class="bussies-title"
      :style="{
        paddingTop: safeAreaInsets?.top ? safeAreaInsets.top + 'px' : '40px',
        height: safeAreaInsets?.top ? 'auto' : '88rpx',
      }"
      >商单&活动</view
    >
    <view class="bussies-inner">
      <view>
        <!-- <view class="flex justify-between mb-10rpx">
          <view class="flex-1 flex">
            <image
              class="h-[96rpx] w-[96rpx]"
              src="/static/images/rocket.png"
              mode="aspectFill"
            />
            <view class="ml-10rpx">
              <view class="text-#000 text-32rpx mb-10rpx font-600"
                >社区活动</view
              >
              <view class="flex items-center">
                <image
                  class="h-[30rpx] w-[30rpx]"
                  src="/static/images/location.png"
                  mode="aspectFill"
                />
                <view class="text-#000 text-24rpx ml-4rpx font-600">北京</view>
                <view class="text-#999 text-24rpx ml-20rpx">1个小时前在线</view>
              </view>
            </view>
          </view>
          <view class="flex mt-20rpx">
            <view class="bg-#000 w-8rpx h-8rpx rounded-8rpx"></view>
            <view class="bg-#000 w-8rpx h-8rpx rounded-8rpx ml-10rpx"></view>
            <view class="bg-#000 w-8rpx h-8rpx rounded-8rpx ml-10rpx"></view>
          </view>
        </view> -->

        <view v-for="item in dataList" :key="item.id">
          <view class="shadow-2xs mb-4">
            <view @click="() => goActivityDetail(item.id)">
              <image class="w-100%" :src="item.coverImage" mode="widthFix" />

              <view class="flex mt-20rpx mb-20rpx items-center">
                <view
                  class="flex items-center bg-#B8F069 rounded-6rpx w-80rpx h-32rpx justify-center"
                >
                  <image
                    class="h-[19rpx] w-[19rpx]"
                    src="/static/images/action-fire.png"
                    mode="aspectFill"
                  />
                  <view
                    v-for="(tag, index) in item.tags.split(',')"
                    :key="index"
                    class="text-16rpx text-#1b1b1b ml-4rpx"
                  >
                    {{ tag.trim() }}
                  </view>
                </view>
                <view class="text-32rpx text-#000 ml-8rpx">{{
                  item.title
                }}</view>
              </view>
              <view class="flex items-center">
                <image
                  class="h-[24rpx] w-[24rpx]"
                  src="/static/images/action-time.png"
                  mode="aspectFill"
                />
                <view class="text-#a6a6a6 text-20rpx ml-10rpx">
                  时间：{{ item.startTime }}~{{ item.endTime }}
                </view>
              </view>
              <view class="flex items-center mb-8rpx mt-8rpx">
                <image
                  class="h-[24rpx] w-[24rpx]"
                  src="/static/images/action-time.png"
                  mode="aspectFill"
                />
                <view class="text-#a6a6a6 text-20rpx ml-10rpx">
                  {{
                    item?.description
                      .replace(/<[^>]+>/g, "") // 去除所有HTML标签
                      .slice(0, 30) + // 截取前12个字符
                    (item?.description.replace(/<[^>]+>/g, "").length > 30
                      ? "..."
                      : "")
                  }}</view
                >
              </view>
              <view class="flex justify-between my-2">
                <view class="flex flex-1 items-center">
                  <!-- <view class="flex items-center">
                <image
                  class="h-[32rpx] w-[32rpx]"
                  src="/static/images/action-user.png"
                  mode="aspectFill"
                />
                <image
                  class="h-[32rpx] w-[32rpx] ml-[-10rpx]"
                  src="/static/images/action-user.png"
                  mode="aspectFill"
                />
                <image
                  class="h-[32rpx] w-[32rpx] ml-[-10rpx]"
                  src="/static/images/action-user.png"
                  mode="aspectFill"
                />
              </view> -->
                  <view class="text-#a6a6a6 text-24rpx ml-20rpx"
                    >{{ item.currentParticipants }}人参与</view
                  >
                </view>
                <view
                  class="text-24rpx h-64rpx flex items-center bussines-button"
                  :style="getStatusStyle(item)"
                >
                  {{ getStatusText(item) }}
                </view>
              </view>
            </view>
            <view
              v-if="
                superManagerPermission(userInfo?.role) ||
                managerPermission(userInfo?.role)
              "
              class="admin-actions grid grid-cols-4 mt-4"
            >
              <button
                class="btn-primary"
                @click="
                  handleUpdateInfo({ type: 'top', id: item.id, title: '置顶' })
                "
                size="mini"
                v-if="item.isTop === 0"
              >
                置顶
              </button>

              <button
                v-if="item.isTop === 1"
                class="btn-info"
                @click="
                  handleUpdateInfo({
                    type: 'untop',
                    id: item.id,
                    title: '取消置顶',
                  })
                "
                size="mini"
              >
                取消置顶
              </button>

              <button
                @click="
                  handleUpdateInfo({
                    type: 'publish',
                    id: item.id,
                    title: '上架',
                  })
                "
                v-if="item.putState === 0"
                class="btn-success"
                size="mini"
              >
                上架
              </button>
              <button
                @click="
                  handleUpdateInfo({
                    type: 'unpublish',
                    id: item.id,
                    title: '下架',
                  })
                "
                v-if="item.putState === 1"
                class="mr-10rpx btn-secondary"
                size="mini"
              >
                下架
              </button>
              <button
                class="btn-danger"
                @click="handleDelete(item.id)"
                size="mini"
              >
                删除
              </button>
              <button
                class="btn-warning"
                @click="handleEdit(item.id)"
                size="mini"
              >
                编辑
              </button>
            </view>
          </view>
        </view>
      </view>
      <view
        style="bottom: 300rpx"
        v-if="userInfo?.role === 2 || userInfo?.role === 3"
      >
        <uni-fab
          ref="fab"
          direction="horizontal"
          horizontal="right"
          :pattern="{
            buttonColor: '#fff',
            iconColor: '#333',
            selectedColor: '#f0f0f0', // 按下状态颜色
            zIndex: 9999,
          }"
          :style="{ bottom: '550rpx' }"
          @fabClick="openPopup"
        />
      </view>
      <!-- 底部弹出层 -->
      <uni-popup
        ref="popupRef"
        type="bottom"
        :is-mask-click="true"
        :safe-area="false"
      >
        <view class="popup-content">
          <view class="flex-1 flex">
            <image
              class="h-[96rpx] w-[96rpx]"
              :src="userInfo?.avatarUrl || '/static/images/avater.jpeg'"
              mode="aspectFill"
            />
            <view class="ml-10rpx flex-1">
              <view class="text-#000 text-32rpx mb-10rpx font-600">{{
                userInfo?.nickname || "七尾有魔法翅膀"
              }}</view>
              <view class="flex items-center justify-between">
                <view class="text-#000 text-24rpx ml-4rpx popup-button"
                  ><uni-icons type="person"></uni-icons>
                  {{ rolesMapping[userInfo?.role] || "未知角色" }}</view
                >
                <button open-type="share" class="custom-btn">
                  <view class="flex items-center justify-between"
                    ><uni-icons type="personadd-filled"></uni-icons>
                    邀请入会</view
                  >
                </button>
              </view>
            </view>
          </view>
          <view class="flex-1 flex mt-20rpx">
            <button @click="goActivity">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/activity.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发活动</text></view
              >
            </button>
            <button @click="goActivity">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/order.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发商单</text></view
              >
            </button>
            <button @click="goInformation">
              <view class="flex items-center justify-between"
                ><image
                  class="h-[36rpx] w-[36rpx]"
                  src="/static/images/news.png"
                  mode="aspectFill"
                />
                <text class="text-36rpx ml-10rpx">发资讯</text></view
              >
            </button>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { getActivityList } from "@/service/activity";
import { useUserStore } from "@/store";
import { storeToRefs } from "pinia";
import { superManagerPermission, managerPermission } from "@/utils";
import { removeActivity, updateActivityInfo } from "@/service/home";

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const { safeAreaInsets } = uni.getSystemInfoSync();
const popupRef = ref<any>(null);
const dataList = ref<any>([]);

const rolesMapping: { [key: number]: string } = {
  1: "普通",
  2: "管理员",
  3: "超级管理员",
};
// 打开弹出层
const openPopup = () => {
  popupRef.value?.open();
};
const goActivity = () => {
  uni.navigateTo({
    url: "/pages-sub/publishActivity/index",
  });
};
const goInformation = () => {
  uni.navigateTo({
    url: "/pages-sub/publishInformation/index",
  });
};

const goActivityDetail = (id) => {
  uni.navigateTo({
    url: `/pages-sub/activeDetail/index?id=${id}`,
  });
};

const statusConfig = {
  notStart: {
    text: "活动未开始",
    bgColor: "#F0F0F0",
    textColor: "#666",
  },
  ongoing: {
    text: "活动进行中",
    bgColor: "#C8FF7A",
    textColor: "#1a1a1a",
  },
  ended: {
    text: "活动结束",
    bgColor: "#FFB6C1",
    textColor: "#D8000C",
  },
};
const parseTime = (timeStr) => {
  // 将空格替换为T以兼容IOS系统
  return Date.parse(timeStr.replace(" ", "T"));
};
const getStatusType = (item) => {
  try {
    const now = Date.now();
    const start = parseTime(item.startTime);
    const end = parseTime(item.endTime);

    if (now < start) return "notStart";
    if (now > end) return "ended";
    return "ongoing";
  } catch (e) {
    console.error("时间解析错误:", e);
    return "ended"; // 默认状态
  }
};
const getStatusStyle = (item) => {
  const type = getStatusType(item);
  return {
    backgroundColor: statusConfig[type].bgColor,
    color: statusConfig[type].textColor,
  };
};
const getStatusText = (item) => {
  return statusConfig[getStatusType(item)].text;
};

const getList = async () => {
  const showData: any = await getActivityList({
    current: "1",
    size: "1000",
  });
  dataList.value = showData.data.records;
};

const updateSelectedTab = () => {
  const currentPath = getCurrentPages().slice(-1)[0]?.route;
  switch (currentPath) {
    case "pages/bussines/index":
      selectedIndex.value = 0;
      break;
    case "pages/news/index":
      selectedIndex.value = 1;
      break;
    case "pages/home/index":
      selectedIndex.value = 2;
      break;
    case "pages/plaza/index":
      selectedIndex.value = 3;
      break;
    case "pages/my/index":
      selectedIndex.value = 4;
      break;
  }
};

onShow(() => {
  getList();
});

const handleUpdateInfo = ({
  type, // 上架: publish 下架：unpublish 置顶：top 取消置顶：untop
  id,
  title, // 上架、下架、置顶、取消置顶
}) => {
  const params = {
    id,
  };
  if (type === "publish") {
    params.putState = 1;
  }
  if (type === "unpublish") {
    params.putState = 0;
  }
  if (type === "top") {
    params.isTop = 1;
  }
  if (type === "untop") {
    params.isTop = 0;
  }
  uni.showModal({
    title: `确定${title}`,
    content: `确定要${title}这个活动？`,
    success: async (res) => {
      if (res.confirm) {
        await updateActivityInfo(params);
        getList();
      }
    },
  });
};

const handleDelete = (id: number) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这个活动？",
    success: async (res) => {
      if (res.confirm) {
        await removeActivity({ ids: id.toString() });
        getList();
      }
    },
  });
};

const handleEdit = (id: number) => {
  uni.navigateTo({
    url: `/pages-sub/publishActivity/index?id=${id}`,
  });
};
</script>

<style lang="scss" scoped>
.bussines-container {
  position: relative;
  min-height: 100vh;
  padding-bottom: 30rpx;
  background: #fff;
  .bussies-bg {
    position: relative;
    z-index: 1;
    width: 350rpx;
    height: 350rpx;
    margin-top: -10rpx;
    margin-left: -20rpx;
    background: #e0ffb5;
    filter: blur(300rpx);
    border-radius: 350rpx;
  }
  .bussies-title {
    position: absolute;
    top: 40rpx;
    left: 40rpx;
    z-index: 2;
    font-size: 52rpx;
    font-weight: bold;
    color: #1a1a1a;
  }
  .bussies-inner {
    padding: 0 32rpx;
    margin-top: -80rpx;
    font-size: 52rpx;
    color: #1a1a1a;
  }
  .bussines-button {
    padding: 0 35rpx;
    border: 1px solid #1a1a1a;
    border-radius: 32rpx;
  }
  .popup-button {
    padding: 10rpx;
    border: 1px solid #1a1a1a;
    border-radius: 32rpx;
  }
}
.popup-content {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}
::v-deep .uni-popup {
  z-index: 9999 !important;
}
.custom-btn {
  background: #e0ffb5;
  border: 1px solid #1a1a1a;
  border-radius: 32rpx;
  padding: 20rpx 10rpx;
  font-size: 24rpx;
  margin-right: 0;
  line-height: 24rpx;
}
/* 通过深度选择器穿透组件样式 */
::v-deep .uni-fab__circle {
  bottom: 250rpx !important; /* 调整垂直位置 */
  z-index: 9999 !important; /* 确保层级最高 */
}
</style>
